import logo from '@/assets/image/logo.png';
import AvatarDef from '@/components/RightContent/AvatarDropdown';
import { LeftOutlined } from '@ant-design/icons';
import { getDvaApp, history, useSelector } from '@umijs/max';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
const LayoutHeader2: React.FC<any> = () => {
  //获取dva里的headerModel
  const headerModel = useSelector((state: any) => state.headerModel);
  const [title, setTitle] = useState<string>('');
  //监听路由变化 在路由变化时更新title和rightCon
  useEffect(() => {
    //执行顺序为 onRouteChange -> LayoutHeader的useEffect -> 页面的useEffect
    //所以这里延迟100ms执行 等待页面的useEffect执行完毕再更新title和rightCon 否则数据会有延迟
    setTimeout(() => {
      setTitle(headerModel.title);
      document.title = headerModel.title + ' - The Mai';
    }, 100);
  }, [history.location.pathname]);

  const back = () => {
    if (history.location.pathname === '/main' || history.location.pathname === '/') {
      history.push('/');
      return;
    } else if (history.location.pathname === '/conversation') {
      history.push('/docList');
      return;
    } else if (history.location.pathname === '/docList') {
      history.push('/');
      return;
    } else {
      history.back();
      return;
    }
  };

  return (
    <div className={styles.containerCN}>
      {!title ? (
        <img
          src={logo}
          alt=""
          style={{ marginLeft: '22px', width: '84px', height: '14px' }}
          onClick={back}
        />
      ) : (
        <div className={styles.title} onClick={back}>
          <LeftOutlined /> {title}
        </div>
      )}
      <div className={styles.rightCon}>
        {/* 如果用解构赋值的话，会导致rightCon更新有延迟 这里调用方法获取最新的rightCon */}
        {getDvaApp()._store.getState().headerModel.rightCon}
        <AvatarDef />
      </div>
    </div>
  );
};

export default LayoutHeader2;
